import concurrent.futures
import configparser
import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By

config = configparser.ConfigParser()
config.read('config.ini')
url_1 = config.get('questionnaire', 'url_1')
url_2 = config.get('questionnaire', 'url_2')
url_3 = config.get('questionnaire', 'url_3')
urls = []
if url_1:
    urls.append(url_1)
if url_2:
    urls.append(url_2)
if url_3:
    urls.append(url_3)

num = {}
second = {}


def answer_question(driver, second):
    try:
        button = driver.find_element(By.CSS_SELECTOR, '.rt-button--bottom')
        button_text = driver.find_element(By.CSS_SELECTOR, '.rt-button--bottom__text').text

        labels = driver.find_elements(By.CSS_SELECTOR, '.rt-checkbox-label')
        question_title = driver.find_element(By.CSS_SELECTOR, '.question_type').text
        if question_title == '单选':
            label = random.choice(labels)
            label.click()
        else:
            selected_checkboxes = random.sample(labels, 2)
            for label in selected_checkboxes:
                label.click()

        if button_text == '下一题':
            button.click()
            time.sleep(second)  # 等待页面加载，根据实际情况调整时间
            answer_question(driver, second)  # 递归调用自身
        else:
            button = driver.find_element(By.CSS_SELECTOR, '.rt-button--bottom')
            button.click()
            driver.quit()
            print("结束答题，退出程序...")
    except Exception as e:
        print(f"发生错误：{e}")
        driver.quit()


def research(second, url):
    options = webdriver.ChromeOptions()
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    options.add_argument(
        'user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')

    driver = webdriver.Chrome(options=options)
    driver.maximize_window()
    driver.get(url)
    time.sleep(3)  # 等待页面加载，根据实际情况调整时间
    answer_question(driver, second)


def forexcu(url):
    for i in range(num):
        print(f"正在执行第{i + 1}次循环")
        research(second, url)


if __name__ == '__main__':
    # 获取用户输入或从其他源读取num
    num = input("请输入循环次数：")
    second = input("请输入问题间隔时间(秒)：")

    # 尝试将输入转换为整数
    try:
        num = int(num)
        second = int(second)
    except ValueError:
        print("错误：输入的不是有效的数字！")
        exit()  # 或者根据应用逻辑选择其他处理方式
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        executor.map(forexcu, urls)
